package com.atguigu.netty.inboundhandlerandoutboundhandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.List;

/**
 * TODO
 * @author wuzz
 * @since 2024/7/15
 */
public class MyClient {


    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 加入一个编码器
                        pipeline.addLast(new MessageToByteEncoder<Long>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
                                System.out.println("客户端编码器");
                                out.writeLong(msg);
                            }
                        });

                        // 入站解码器
                        pipeline.addLast(new ByteToMessageDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                                System.out.println("客户端解码器");
                                if (in.readableBytes() >= 8) {
                                    out.add(in.readLong());
                                }
                            }
                        });

                        // 加入一个自定义handler用来处理业务
                        pipeline.addLast(new SimpleChannelInboundHandler<Long>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
                                System.out.println("客户端从服务端拿到数据信息：：" + msg);
                            }

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("MyClientHandler发送数据");
                                ctx.writeAndFlush(123456L);
                            }
                        });
                    }
                });
        bootstrap.connect("127.0.0.1", 8888);
    }

}
